package com.hyhy.hycloud.commons.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.hyhy.hycloud.commons.helper.HycloudDateFormat;
import com.hyhy.hycloud.commons.helper.HycloudLocalDateDeserializer;
import com.hyhy.hycloud.commons.helper.HycloudLocalDateTimeDeserializer;
import com.hyhy.hycloud.commons.helper.HycloudLocalTimeDeserializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author lanpengfei
 * @date 2018/12/24
 */
@Configuration
@ConditionalOnClass(ObjectMapper.class)
@EnableConfigurationProperties(JacksonProperties.class)
public class WebObjectMapperConfig implements Jackson2ObjectMapperBuilderCustomizer {
    @Autowired
    private JacksonProperties jacksonProperties;

    @Override
    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        DateFormat dateFormat = new HycloudDateFormat(new ObjectMapper().getDateFormat());
        if (jacksonProperties.getTimeZone() != null) {
            dateFormat.setTimeZone(jacksonProperties.getTimeZone());
        }
        jacksonObjectMapperBuilder.dateFormat(dateFormat);

        JavaTimeModule module = new JavaTimeModule();

        module.addDeserializer(LocalDateTime.class, HycloudLocalDateTimeDeserializer.INSTANCE);
        module.addDeserializer(LocalDate.class, HycloudLocalDateDeserializer.INSTANCE);
        module.addDeserializer(LocalTime.class, HycloudLocalTimeDeserializer.INSTANCE);

        if (!StringUtils.isEmpty(jacksonProperties.getDateFormat())) {
            module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat())));
        }
        jacksonObjectMapperBuilder.modules(module);
    }
}
